package http

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Name struct {
	Name string
}

func login(c *gin.Context) {
	if c.Request.Method == http.MethodGet {
		c.HTML(http.StatusOK, "login.html", nil)
		return
	}
	loginName, _ := c.GetPostForm("LoginName")
	password, _ := c.GetPostForm("Password")
	if loginName != "" && password != "" {
		user, _ := userService.QueryByLoginName(loginName)
		if user == nil {
			c.JSON(http.StatusOK, "用户名错误")
			return
		}
		if password != user.Password {
			c.JSON(http.StatusOK, "密码错误")
			return
		}
		session := sessions.Default(c)
		session.Set(SessionKey, user)
		session.Save()
	}
	c.HTML(http.StatusOK, "book/list_1.html", newHTMLData(c, nil))
}

func logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete(SessionKey)
	session.Save()
	c.HTML(http.StatusOK, "login.html", nil)
	return
}
